package gov.kqqzyyy.monkey.radiologyscreen.mytools;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.socks.library.KLog;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

import gov.kqqzyyy.monkey.radiologyscreen.adapter.MyPatientAdapter;
import gov.kqqzyyy.monkey.radiologyscreen.receiver.DownLoadReceiver;
import gov.kqqzyyy.monkey.radiologyscreen.receiver.UpdateReceiver;
import gov.kqqzyyy.monkey.radiologyscreen.service.UpdateService;
import gov.kqqzyyy.monkey.radiologyscreen.ui.FragmentPreferences;
import gov.kqqzyyy.monkey.radiologyscreen.ui.SplashActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Monkey on 2017/11/25.
 * 基类
 */

public class MyBaseActivity extends AppCompatActivity {

    private TextView timeTextView;
    private TextView versionTextView;
    private ListView rollListView;

    private long deteDelta = 0;
    Date localDateTime;
    String showDate;

    private MyHandler handler;
    private Timer clockTimer;
    private Timer scrollTimer;
    private MyApplication myApplication;
    //    private SharedPreferences mSharedPreferences;
    private Call<String> systemTimeCall;
    private DownLoadReceiver downLoadReceiver;
    private UpdateReceiver updateReceiver;
    private Intent serviceIntent;
    private UploadListener uploadListener;
    private ProgressDialogFragment progressDialogFragment;
    private boolean isUploading = false;
    private boolean moveToBottom = true;
    private Thread ftpThread;

    public void setTimeTextView(TextView timeTextView) {
        this.timeTextView = timeTextView;
    }

    public void setVersionTextView(TextView versionTextView) {
        this.versionTextView = versionTextView;
    }

    public void setRollListView(ListView rollListView) {
        this.rollListView = rollListView;
    }

    public void doGetServerTime() {
        systemTimeCall = MyServiceUtil.getSystemTimeCall();
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String result = response.body();
                if (result != null) {
                    result = result.replace("\"", "");
                    try {
                        Date serverDate = myApplication.getSdfDateTime().parse(result);
                        deteDelta = serverDate.getTime() - new Date(System.currentTimeMillis()).getTime();
                        Toast.makeText(getApplicationContext(), "系统时间已同步！", Toast.LENGTH_SHORT).show();
                    } catch (ParseException e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "获取系统时间格式化出错！", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "获取服务器时间出错：" + t.toString(), Toast.LENGTH_SHORT).show();
            }
        };
        systemTimeCall.enqueue(callback);

    }

    public MyApplication getMyApplication() {
        return myApplication;
    }

    public String getShowDate() {
        return showDate;
    }

    public void doStartService() {
        startService(serviceIntent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new MyHandler(this);
        myApplication = (MyApplication) getApplication();
//        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        downLoadReceiver = new DownLoadReceiver(this);
        IntentFilter downLoadFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(downLoadReceiver, downLoadFilter);
        updateReceiver = new UpdateReceiver(this);
        IntentFilter updateFilter = new IntentFilter("updatebroadcast");
        registerReceiver(updateReceiver, updateFilter);
        IntentFilter restartFilter = new IntentFilter();
        restartFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(SystemTimeReceiver, restartFilter);

        serviceIntent = new Intent(getApplicationContext(), UpdateService.class);
        uploadListener = (currentStep, uploadSize, file) -> {
            KLog.d("APE", currentStep);
            switch (currentStep) {
                case FtpUtil.FTP_UPLOAD_SUCCESS:
                    KLog.d("APE", file.getName() + " 上传完成");
                    break;
                case FtpUtil.FTP_UPLOAD_LOADING:
                    long fize = file.length();
                    float num = (float) uploadSize / (float) fize;
                    int result = (int) (num * 100);
                    KLog.d("APE", "downloading :" + result);
                    break;
                case FtpUtil.FTP_DISCONNECT_SUCCESS:
                    stopUploadThread();
                    break;
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        cancelClockTimer();
        clockTimer = new Timer();
        clockTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 0x11;
                handler.sendMessage(message);
            }
        }, 1, 1000);
        cancelScrollTimer();
        scrollTimer = new Timer();
        scrollTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (rollListView != null) {
                    rollingListView(rollListView);
                }
            }
        }, 5000, 5000);
        deleteOldApk();
    }

    @Override
    protected void onStop() {
        super.onStop();
        cancelClockTimer();
        cancelScrollTimer();
        if (systemTimeCall != null && systemTimeCall.isExecuted()) {
            systemTimeCall.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(downLoadReceiver);
        unregisterReceiver(updateReceiver);
    }

    private void cancelClockTimer() {
        if (clockTimer != null) {
            clockTimer.cancel();
            clockTimer = null;
        }
    }

    private void cancelScrollTimer() {
        if (scrollTimer != null) {
            scrollTimer.cancel();
            scrollTimer = null;
        }
    }

    //显示时间
    protected void setClock() {
        if (timeTextView != null) {
            localDateTime = new Date(System.currentTimeMillis());
            localDateTime.setTime(localDateTime.getTime() + deteDelta);
            showDate = myApplication.getSdfWeekDay().format(localDateTime);
            String text = showDate.substring(0, 11) + "\n" + showDate.substring(11, 14) + " " + showDate.substring(14);
            timeTextView.setText(text);
        }
    }

    public void cancelProgressDialog() {
        if (progressDialogFragment != null && progressDialogFragment.getDialog() != null) {
            progressDialogFragment.getDialog().dismiss();
        }
    }

    public void showProgressDialog() {
        cancelProgressDialog();
        progressDialogFragment = new ProgressDialogFragment();
        progressDialogFragment.setMessage("下载中");
        progressDialogFragment.show(getFragmentManager(), "downLoading");
    }

    private void deleteOldApk() {
        File fileCache = new File(String.valueOf(getApplicationContext().getExternalCacheDir()));
        String path = fileCache.getParentFile() + "/files/" + Environment.DIRECTORY_DOWNLOADS;
        File fileDir = new File(path);
        if (fileDir.isDirectory()) {
            File[] files = fileDir.listFiles();
            if (files.length > 0) {
                for (File file : files
                        ) {
                    if (file.exists()) {
                        if (file.delete()) {
                            KLog.d("APE", file.getName() + "删除成功！");
                        } else {
                            KLog.d("APE", file.getName() + "删除失败！");
                        }
                    }
                }
            }
        }
    }

    public void doSetVersion() {
        versionTextView.setText(myApplication.getVersionName());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                Intent intent = new Intent(getApplicationContext(), FragmentPreferences.class);
                startActivity(intent);
                finish();
                return true;
            case KeyEvent.KEYCODE_BACK:
                Intent intent1 = new Intent(getApplicationContext(), SplashActivity.class);
                startActivity(intent1);
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private static class MyHandler extends Handler {
        WeakReference<MyBaseActivity> mActivity;

        MyHandler(MyBaseActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MyBaseActivity activity = mActivity.get();
            switch (msg.what) {
                case 0x11://
                    activity.setClock();
                    break;
            }
        }
    }

    // 更新提示对话框
    public void showUpdateDialog(int newVerCode, String newVerName) {
        cancelProgressDialog();
        String message = "";
        final Intent intent = new Intent("toUpdateService");
        message += "当前版本：" + CurrentVersion.getVerName(this) + "\n";
        message += "版本号：" + CurrentVersion.getVerCode(this) + "\n";
        message += "发现新版本：" + newVerName + "\n";
        message += "版本号：" + newVerCode + "\n";
        message += "是否更新？";
        Dialog dialog = new AlertDialog.Builder(this)
                .setTitle("软件更新")
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("确定", (dialogInterface, i) -> {
                    intent.putExtra("toservice", 0x11);
                    sendBroadcast(intent);
                    dialogInterface.dismiss();
                    showProgressDialog();
                })
                .setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss())
                .create();
        dialog.show();
    }

    public void doFlushData() {
    }

    private LinkedList<File> doGetUploadFiles() {
        String logPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "crash" + File.separator;
        File crashDir = new File(logPath);
        Date deleDate;
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE) - 1);
        String deleteDateString = myApplication.getSdfDate().format(calendar.getTime());
        try {
            deleDate = myApplication.getSdfDate().parse(deleteDateString);
        } catch (ParseException e) {
            deleDate = new Date();
            e.printStackTrace();
        }
        if (crashDir.isDirectory()) {
            File[] files = crashDir.listFiles();
            LinkedList<File> fileList = new LinkedList<>();
            for (File file : files
                    ) {
                String fileName = file.getName();
                if (fileName.contains(".log") && fileName.startsWith("yfp-")) {
                    String fileDateString = fileName.substring(4, 14);
                    try {
                        Date fileDate = myApplication.getSdfDate().parse(fileDateString);
                        if (fileDate.getTime() < deleDate.getTime()) {
                            fileList.add(file);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
            }
            return fileList;
        }
        return null;
    }

    public void doUploadLogFile() {
        final LinkedList<File> fileList = doGetUploadFiles();
        if (fileList != null && fileList.size() > 0) {
            if (!isUploading) {
                isUploading = true;
                ftpThread = new Thread(() -> {
                    while (isUploading) {
                        try {
                            new FtpUtil().uploadMultiFile(fileList, uploadListener, true);
                        } catch (IOException e) {
                            stopUploadThread();
                            KLog.d("APE", e.getMessage());
                            e.printStackTrace();
                        }
                    }
                });
                ftpThread.start();
            }
        } else {
            Toast.makeText(getApplicationContext(), "没有需要上传的日志！", Toast.LENGTH_SHORT).show();
        }
    }

    private void stopUploadThread() {
        isUploading = false;
        if (ftpThread != null && ftpThread.isAlive()) {
            ftpThread.interrupt();
            ftpThread = null;
        }
    }

    private BroadcastReceiver SystemTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Objects.equals(intent.getAction(), Intent.ACTION_TIME_TICK)) {
                if (isRestartTime()) { //次日、11点 重启
                    new CountDownTimer(5000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                        }

                        @Override
                        public void onFinish() {
                            Intent intent1 = new Intent(getApplicationContext(), SplashActivity.class);
                            startActivity(intent1);
                        }
                    }.start();
                }
                new CountDownTimer(2000, 1000) {

                    @Override
                    public void onTick(long millisUntilFinished) {

                    }

                    @Override
                    public void onFinish() {
                        doFlushData();
                    }
                }.start();
            }
        }
    };

    private boolean isRestartTime() {
        String timeNow = myApplication.getSdfTime().format(localDateTime);
        return timeNow.compareTo("23:59:55") > 0 || timeNow.compareTo("00:00:05") < 0;
    }

    private void rollingListView(ListView listView) {
        MyPatientAdapter adapter = (MyPatientAdapter) listView.getAdapter();
        List list = adapter.getDataList();
        if (list != null && list.size() > 0) {
            int lastPos = listView.getLastVisiblePosition();
            if (lastPos < list.size() - 1) {
                if (moveToBottom) {
                    moveToBottom = false;
                    listView.smoothScrollToPosition(lastPos);
                } else {
                    moveToBottom = true;
                    listView.smoothScrollToPosition(lastPos + 1);
                }
            } else {
                if (moveToBottom) {
                    listView.smoothScrollToPosition(list.size() - 1);
                } else {
                    listView.smoothScrollToPosition(1);
                }
                moveToBottom = !moveToBottom;
            }
        }
    }

}
